#!/usr/bin/python
# -*- coding: utf-8 -*-  # 编码声明，确保支持非 ASCII 字符

import json
import time
try:
    # Python 2
    import urllib
    import urllib2
    import httplib
except ImportError:
    # Python 3
    import urllib.request as urllib_request
    import urllib.parse as urllib_parse
    import http.client as httplib

def load_config():
    ''' 加载配置文件 '''
    config = {}
    try:
        with open('/opt/osmt-client/etc/https.yml', 'r') as config_file:
            for line in config_file:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                if ':' in line:
                    key, value = line.split(':', 1)
                    config[key.strip()] = value.strip()
    except FileNotFoundError:
        print("配置文件未找到")
        return None

    url = config.get('server_url')  # 获取 'server_url'
    id_value = config.get('node_id')  # 获取 'node_id'

    if not url or not id_value:
        print("配置文件缺少必要的 'server_url' 或 'node_id'")
        return None

    return url, id_value

def handle_response(response_content):
    """ 处理 JSON 格式的响应 """
    try:
        response_json = json.loads(response_content)
        code = response_json.get('code')
        # 判断返回的 code 是否为 0（表示操作成功）
        if code == 0:
            print("操作成功")
            return True  # 请求成功
        else:
            print("操作失败，错误代码：{}, 错误信息：{}".format(code, response_json.get('msg')))
            return False  # 操作失败，返回 False
    except ValueError:
        print("响应内容不是有效的 JSON 格式，原始响应内容:")
        print(response_content)
        return False  # 如果响应内容不是 JSON 格式，返回 False
    
    
def send_post_request(url, data, max_retries=3):
    """ 发送 POST 请求 """
    json_data = json.dumps(data, ensure_ascii=False)
    headers = {'Content-Type': 'application/json'}
    retries = 0
    
    while retries < max_retries:
        # 发送 POST 请求
        if 'urllib2' in globals():
            req = urllib2.Request(url, json_data.encode('utf-8'), headers)
            response = urllib2.urlopen(req)
        else:
            req = urllib_request.Request(url, json_data.encode('utf-8'), headers)
            response = urllib_request.urlopen(req)
        
        # 获取响应状态码
        if response.getcode() == 200:
            content = response.read().decode('utf-8')  # 获取响应体内容并解码
            handle_response(content)  # 处理响应体
            break  # 如果状态码是 200，退出循环
        else:
            retries += 1
            print("请求失败，状态码: {}. 正在重试... ({}/{})".format(response.status, retries, max_retries))
            time.sleep(2)  # 等待 2 秒后重试

# 重启后执行迁移后检查
def check_transfer_status():
    pass
def main():
    url, id_value = load_config()
    send_post_request(url,{
        "id": id_value,
        "stat": 0,
        "type": 1,
        "error": None})

if __name__ == '__main__':
    main()
    